package com.ruicar.afs.cloud.apply.pre.loan.mq.receiver;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.business.service.WorkflowAgencyTaskService;
import com.ruicar.afs.cloud.apply.common.entity.ApplyOrderInfo;
import com.ruicar.afs.cloud.apply.common.entity.ApplyRemindDetails;
import com.ruicar.afs.cloud.apply.common.entity.WorkflowAgencyTask;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.pre.loan.mq.sender.CaseSubmitInfoSender;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyOrderInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyRemindDetailsService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.BusinessStateInEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ResultBooleanEnum;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.CallBackApplyDto;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.CallBackApplyResultDto;
import com.ruicar.afs.cloud.common.mq.rabbit.listener.AfsMqBizProcessor;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.parameter.commom.enums.AProveBusinessTypeEnum;
import com.ruicar.afs.cloud.parameter.commom.enums.OrderOprType;
import com.ruicar.afs.cloud.parameter.commom.enums.WhetherEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;

@AllArgsConstructor
@Slf4j
@Component
@ConditionalOnProperty(prefix = "com.ruicar.afs.cloud.mq.rabbit", name = "enable")
public class ApproveCallBackApplyProcessor implements AfsMqBizProcessor<CallBackApplyDto> {

    private final ApplyOrderInfoService applyOrderInfoService;
    private final CaseSubmitInfoSender caseSubmitInfoSender;
    private final WorkflowAgencyTaskService workflowAgencyTaskService;
    private final ApplyRemindDetailsService applyRemindDetailsService;

    /**
     * <p>description:</p>
     * 审批撤回申请
     * @param entity
     * @author ma_xueyu
     * @created 2020年9月15日
     * @version 1.0
     */
    @Override
    public boolean processMessage(CallBackApplyDto entity) throws Exception {
        log.info("接收审批撤回申请："+ JSON.toJSONString(entity));
        ResultBooleanEnum resultBooleanEnum=ResultBooleanEnum.FALSE;
        //根据当案件内部状态处理审批端撤回申请
        ApplyOrderInfo orderInfo = applyOrderInfoService.getOne(Wrappers.<ApplyOrderInfo>query().lambda()
                .eq(ApplyOrderInfo::getApplyNo, entity.getApplyNo()));
        Assert.isTrue(ObjectUtil.isNotNull(entity.getBusinessStateIn()), "业务状态不能为空");

        if(AfsEnumUtil.key(BusinessStateInEnum.REVISE_PARSE).equals(entity.getBusinessStateIn())){
            if(ApplyConstants.APPLY_STATUS_SUSPEND.equals(orderInfo.getApplyStatus())){
                //审批退回待办任务
                List<WorkflowAgencyTask> workflowAgencyTaskList = workflowAgencyTaskService.list(Wrappers.<WorkflowAgencyTask>lambdaQuery()
                        .eq(WorkflowAgencyTask::getBusinessNo,orderInfo.getApplyNo())
                        .eq(WorkflowAgencyTask::getBusinessType,String.valueOf(OrderOprType.NORMAL))
                        .eq(WorkflowAgencyTask::getStatus, AProveBusinessTypeEnum.BACK.getCode())
                        .orderByDesc(WorkflowAgencyTask::getCreateTime));
                //审批退回留言
                List<ApplyRemindDetails> applyRemindDetailsList = applyRemindDetailsService.list(Wrappers.<ApplyRemindDetails>lambdaQuery()
                        .eq(ApplyRemindDetails::getApplyNo,orderInfo.getApplyNo())
                        .eq(ApplyRemindDetails::getRemindType,AProveBusinessTypeEnum.BACK.getCode())
                        .orderByDesc(ApplyRemindDetails::getCreateTime));
                if(CollectionUtil.isNotEmpty(workflowAgencyTaskList)){
                    //判断经销商是否已经打开
                    if(WhetherEnum.YES.getIndex().equals(workflowAgencyTaskList.get(0).getIsOpen())){
                        resultBooleanEnum=ResultBooleanEnum.FALSE;
                    }else{
                        //未打开可直接撤回
                        resultBooleanEnum=ResultBooleanEnum.TRUE;
                        //删除当前修订回复待办任务
                        workflowAgencyTaskService.removeById(workflowAgencyTaskList.get(0).getId());
                        //删除最新留言
                        if(CollectionUtil.isNotEmpty(applyRemindDetailsList)){
                            applyRemindDetailsService.removeById(applyRemindDetailsList.get(0).getId());
                        }
                        //修订暂停状态的撤回申请：恢复为待审核状态
                        orderInfo.setApplyStatus(ApplyConstants.APPLY_STATUS_PENDING);
                        orderInfo.setUpdateTime(new Date());
                        applyOrderInfoService.updateById(orderInfo);
                    }
                }
            }
            //判断是否为审批重试撤回
            if(ApplyConstants.APPLY_STATUS_PENDING.equals(orderInfo.getApplyStatus())){
                resultBooleanEnum=ResultBooleanEnum.TRUE;
            }
            //回复审批撤回结果
            AfsTransEntity<CallBackApplyResultDto> transEntity = new AfsTransEntity<>();
            CallBackApplyResultDto callBackApplyResultDto = new CallBackApplyResultDto();
            callBackApplyResultDto.setApplyNo(entity.getApplyNo());
            callBackApplyResultDto.setScheduleId(entity.getScheduleId());
            callBackApplyResultDto.setCallbackUsername(entity.getCallbackUsername());
            callBackApplyResultDto.setCallBackUserRealName(entity.getCallBackUserRealName());
            callBackApplyResultDto.setResult(AfsEnumUtil.key(resultBooleanEnum));
            transEntity.setTransCode(MqTransCode.AFS_POS_APPLY_CASE_CTM_APPROVE_CALL_BACK);
            transEntity.setData(callBackApplyResultDto);
            caseSubmitInfoSender.approveCallBackApplyResultMessageSender(transEntity);
        }else{
            throw new RuntimeException("当前案件不可撤回");
        }
        return true;
    }

    @Override
    public MqTransCode getCode() {
        return MqTransCode.AFS_POS_APPLY_CASE_CTM_APPROVE_CALL_BACK;
    }
}
